package com.hunliji.monitor.share.utils;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 文字工具
 * @author wuchen
 */
@Slf4j
public class WordsUtil {
    private static final String CHINA_MATCHES = "[\\u4e00-\\u9fa5]";
    /**
     * 根据中文获取拼音
     * @param word
     * @return
     */
    public static String getPinYin(String word){
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        //该选项表示汉语拼音以小写字母输出
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        //该选项表示输出汉语拼音时没有音号或音标
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        //该选项表示“u”的输出为“v”
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] arrays = word.trim().toCharArray();
        String result = "";
        try {
            for (int i=0;i<arrays.length;i++) {
                char ti = arrays[i];
                //匹配是否是中文
                if(Character.toString(ti).matches(CHINA_MATCHES)){
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti,format);
                    result += temp[0];
                    if(i<arrays.length-1){
                        result = result + "_";
                    }
                }else{
                    result += ti;
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return result;
    }
}
